package util

import "sync"

// SyncMap 类型安全的 并发安全 哈希表
type SyncMap[keyType comparable, valueType any] struct {
	mp sync.Map
}

func (sm *SyncMap[keyType, valueType]) Load(key keyType) (value valueType) {
	valueInterface, ok := sm.mp.Load(key)
	if !ok {
		return
	}
	return valueInterface.(valueType)
}

func (sm *SyncMap[keyType, valueType]) MustLoad(key keyType) (value valueType) {
	valueInterface, _ := sm.mp.Load(key)
	return valueInterface.(valueType)
}

func (sm *SyncMap[keyType, valueType]) LoadExists(key keyType) (value valueType, exists bool) {
	valueInterface, exists := sm.mp.Load(key)
	if !exists {
		return
	}
	return valueInterface.(valueType), exists
}

func (sm *SyncMap[keyType, valueType]) Store(key keyType, value valueType) {
	sm.mp.Store(key, value)
}

func (sm *SyncMap[keyType, valueType]) Delete(key keyType) {
	sm.mp.Delete(key)
}

func (sm *SyncMap[keyType, valueType]) LoadOrStore(key keyType, value valueType) (actual valueType, loaded bool) {
	actualInterface, loaded := sm.mp.LoadOrStore(key, value)
	actual = actualInterface.(valueType)
	return
}
